import DetailsHead from "@/components/detailsHead/Header";
import Layer from "@/components/detailsLayer/Layer";
import Attachments from "@basic/Attachments.vue";
import SimpleList from "@components/orderDetail/SimpleList.vue";
import Information from "@/components/track/Information.vue";
import Descriptions from "./components/Descriptions.vue";
import QuoteList from "./components/QuoteList.vue";
import TotalList from "./components/TotalList.vue";
import Reject from "./components/Reject.vue";
import TransportQuote from "./components/TransportQuote.vue";
import PayType from "./components/PayType.vue";
import Bargain from "./components/Bargain.vue";
import { quotation, transport, track } from "@/api/index";
import { returnThousandDigit, volumeOrWeightConversion } from "@/libs/util.js";
import { QuoteCstArr, QuoteCarrArr, totalData, quotationCostName, transportQuoteInfoArr, } from "@components/orderDetail/orderData";
import { STATUS_LABEL, QUOTATION_COLUMN } from "./quotation.mixin";

export default {
  name: "quoteDetail",
  components: {
    Attachments,
    DetailsHead,
    Layer,
    TotalList,
    SimpleList,
    QuoteList,
    Descriptions,
    Information,
    Reject,
    TransportQuote,
    Bargain,
    PayType,
  },
  data () {
    return {
      loading: false,
      api: quotation,
      transportQuoteInfoArr,
      totalData,
      waybillDetails: {},
      files: [], //附件
      buttonStatus: null,
      quoteData: {},
      quoteDetail: {},
      feeTypeArr: [],  // 补充费用-已存在费用的费用项
      quoteTotal: 0, //运单费用合计
      bargainTotal: 0, //补充费用合计
      minimumFee: 0, //最低费用
      carrierExtraType: 0, // 是否是个体司机
      visible: false,      // 拒绝弹窗
      bargainSwitch: false,  // 议价开关
      matchId: null, //合约匹配id
      refresh: false, //价格重算
      remarks: null,
      track: [], // 跟踪信息
      isTrack: false, // 跟踪信息标题显示
      tips: `（零担/整车+提货费+送货费+装货费+卸货费）< 最低费用，订单匹配合约最低费用合计=最低费用+附加费+保险费+税费`,
      quotationId: null,
      status: null
    };
  },
  computed: {
    waybillType () {
      // 10: 发货方 20：承运方
      return this.waybillDetails?.waybillType;
    },
    configData () {
      return this.waybillType === 10 ? QuoteCstArr : QuoteCarrArr;
    },
    surcharge () {
      return this.quoteDetail?.surcharge || (this.$route.query?.surcharge?.toString() === 'true');
    },
    // 报价-议价
    waybillQuoteBargain () {
      const { name } = this.$route
      return name === 'waybillQuoteBargain' ? true : this.bargainSwitch;
    },
    closeLabel () {
      return ['32', '14'].includes(this.status) ? '关闭' : '返回'
    },
    arrivePayFeeFlag () {
      return this.waybillDetails?.finance?.arrivePayFeeFlag;
    },
    collectionFeeFlag () {
      return this.waybillDetails?.finance?.collectionFeeFlag;
    },
    prepayFeeFlag () {
      return this.waybillDetails?.finance?.prepayFeeFlag;
    },
    // 运单收付款
    waybillPrice () {
      return this.waybillDetails?.waybillPrice
    },
    content () {
      const { carrier, customer } = this.waybillDetails
      // 承运方报价
      if (this.waybillType === 20) {
        if (carrier?.carrierType === 0) {
          return '线下'
        }
        if (carrier?.carrierType === 1 && carrier.carrierExtraType == 0) {
          return '线上'
        }
      } else {
        switch (customer?.showCustomerType) {
          case 0:
            return '线下';
          case 1:
            return '线上';
          default:
            return ''
        }
      }
      return ''
    },
    iconName () {
      const { carrier, customer } = this.waybillDetails
      // 承运方报价
      if (this.waybillType === 20) {
        if (carrier?.carrierType === 0) {
          return 'xianxia'
        }
        if (carrier?.carrierType === 1 && carrier.carrierExtraType == 0) {
          return 'xianshang'
        }
      } else {
        switch (customer?.showCustomerType) {
          case 0:
            return 'xianxia';
          case 1:
            return 'xianshang';
          default:
            return ''
        }
      }
      return ''
    },
    btnGroup () {
      // 待报价、草稿、按单报价-被拒绝
      let group = [
        { label: "发送", status: 10 },
        { label: "保存", status: 20 }
      ];
      // 草稿、被拒绝，可关闭报价单
      if (["0", "3"].includes(this.status)) {
        group.push({ label: "关闭", status: 110 })
      }
      // 待审核，可撤回报价单
      if (this.status === "1") {
        group = [{ label: "撤回", status: 40 }];
      }
      // 补充报价-被拒绝
      if (this.status === "3" && this.surcharge) {
        group = [
          { label: "发送", status: 100 }, //发送补充议价
          { label: "关闭", status: 110 }
        ];
      }
      // 议价、补充报价-议价
      if (this.waybillQuoteBargain) {
        group = [
          { label: "发送", status: 50 } //发送议价
        ];
      }
      // 议价-合同编号进入
      if (this.status === "8" && !this.waybillQuoteBargain) {
        group = [
          { label: "同意", status: 30 }, //同意报价
          { label: "议价", status: 70 } //跳转议价
        ];
      }
      // 审核报价-合同编号进入
      if (this.status === "11" && !this.waybillQuoteBargain) {
        group = [
          { label: "同意", status: 30 }, //同意报价
          { label: "拒绝", status: 60 },
          { label: "议价", status: 70 } //70跳转议价
        ];
      }
      // 补充报价
      if (this.status === "2") {
        group = [
          { label: "发送", status: 90 } //发送补充报价
        ];
      }
      // 议价中、已关闭
      if (["18", "32", '14'].includes(this.status)) {
        group = [];
      }
      return group;
    },
    //运单报价禁用编辑
    transportDisabled () {
      let transportStatus = ["1", "2", "18", "32", "14"];
      if (transportStatus.includes(this.status)
        || (this.status === "3" && this.surcharge)
        || (['8', '11'].includes(this.status) && !this.waybillQuoteBargain)
        || (this.waybillQuoteBargain && this.surcharge)
      ) {
        return true;
      }
      return false
    },
    //补充费用报价禁用编辑
    addDisabled () {
      let addStatus = ["1", "6", "18", "32", "14"];
      if (addStatus.includes(this.status)
        || (['8', '11'].includes(this.status) && !this.waybillQuoteBargain)
      ) {
        return true;
      }
      return false
    },
    //付款方式禁用编辑
    payDisabled () {
      // 付款方式报价禁用编辑 1待审核 8议价 11审核报价 32关闭
      let payStatus = ["1", "18", "32", "14"];
      if (payStatus.includes(this.status)
        || (['8', '11'].includes(this.status) && !this.waybillQuoteBargain)
      ) {
        return true;
      }
      return false
    },
    //补充费用新增操作禁用
    addActionDisabled () {
      // 审核报价-议价、议价审核方 disabled：true
      if (this.status === '11' && (this.waybillQuoteBargain || this.bargainSwitch)
        || (!this.initiator && (this.waybillQuoteBargain || this.bargainSwitch))
      ) {
        return true;
      }
      return false;
    },
    //备注禁用编辑
    descDisabled () {
      //备注禁用编辑 1待审核 2补充报价 8议价 11审核报价 32 14 关闭
      let descStatus = ["1", "2", "8", "11", "18", "32", "14"];
      if (descStatus.includes(this.status) || this.waybillQuoteBargain) {
        return true;
      }
      return false;
    },
    // 运单费用列
    wayBillColumn () {
      let colums = [];

      // 报价费用结构转换
      for (let i in this.waybillDetails.transportRequirement) {
        if (QUOTATION_COLUMN.includes(i) && this.waybillDetails.transportRequirement[i]) {
          if (this.waybillDetails?.carrier?.carrierExtraType && ['pick', 'deliver', 'insure'].includes(i)) {
            console.log("========i", i)
          } else {
            colums.push({
              name:
                i === "transportMode"
                  ? this.waybillDetails.transportRequirement[i] === 2
                    ? "full"
                    : "less"
                  : i,
              label:
                i === "transportMode" && this.waybillDetails.transportRequirement[i] === 2
                  ? "整车费"
                  : quotationCostName[i],
              type: this.transportDisabled ? "text" : "input" //运单报价禁用编辑
            });
          }
        }
      }
      let first = colums.splice(
        colums.findIndex(
          (item) => item.name === "full" || item.name === "less"
        ),
        1
      );
      let deliver = colums.splice(
        colums.findIndex((item) => item.name === "deliver"),
        1
      );
      let last = colums.splice(
        colums.findIndex((item) => item.name === "insure"),
        1
      );
      colums = [...first, ...colums, ...deliver, ...last];

      /** 个体司机 整车、零担字段名称替换为运费，不显示提货 pick 送货 deliver 保价 insure */
      if (this.carrierExtraType) {
        colums[0].label = "运费"
      } else {
        colums.push({
          name: "tax",
          label: "税费",
          type: this.transportDisabled ? "text" : "input"
        })
      }
      colums.push({
        name: "quoteTotal",
        label: "报价费用",
        type: "total"
      });
      if (this.quoteDetail?.minimumFee) {
        colums.splice(colums.length - 1, 0, { name: "minimumFee", label: "最低费用", type: "text" });
      }

      return colums;
    },
    // 运单费用
    priceList () {
      let priceArr = [];
      if (this.quotationId && this.quoteDetail) {
        priceArr = [{
          pick: this.quoteDetail?.pickFee || 0, //提货费
          deliver: this.quoteDetail?.deliverFee || 0, //送货费
          onLoad: this.quoteDetail?.loadFee || 0, //装货费
          offLoad: this.quoteDetail?.unloadFee || 0, //卸货费
          insure: this.quoteDetail?.insureFee || 0,  //保险费
          tax: this.quoteDetail?.taxFee || 0, //税费
          minimumFee: this.quoteDetail?.minimumFee || 0 //最低费用
        }];
        // transportMode 1零担 2整车
        if (this.waybillDetails?.transportRequirement?.transportMode === 1) {
          priceArr[0].less = this.quoteDetail?.transportFee || 0;
        } else {
          priceArr[0].full = this.quoteDetail?.transportFee || 0;
        }

        let priceTotal = 0; //运单费用合计
        if (this.quoteDetail?.minimumFee) {
          priceTotal = this.quoteDetail.minimumFee + priceArr[0].tax + priceArr[0].insure
        } else {
          // 计算运单费用总和
          for (let key in priceArr[0]) {
            priceTotal += priceArr[0][key];
          }
        }
        priceArr[0].quoteTotal = Number(priceTotal.toFixed(2));
        this.quoteTotal = Number(priceTotal.toFixed(2));
        // 议价-议价前费用显示
        if (this.status === '8' || this.waybillQuoteBargain) {
          priceArr[0].lessFeeBefore = this.quoteDetail?.transportFeeBefore;
          priceArr[0].fullFeeBefore = this.quoteDetail?.transportFeeBefore;
          priceArr[0].pickFeeBefore = this.quoteDetail?.pickFeeBefore;
          priceArr[0].deliverFeeBefore = this.quoteDetail?.deliverFeeBefore;
          priceArr[0].onLoadFeeBefore = this.quoteDetail?.loadFeeBefore;
          priceArr[0].offLoadFeeBefore = this.quoteDetail?.unloadFeeBefore;
          priceArr[0].insureFeeBefore = this.quoteDetail?.insureFeeBefore;
          priceArr[0].taxFeeBefore = this.quoteDetail?.taxFeeBefore;
        }
      }
      return priceArr;
    },
    // 补充费用
    addCostList () {
      let bargainTotal = 0;     //附加费用合计
      let surchargeData = [];   // 附加费用列表数据源
      let surchargeFees = this.quoteDetail?.surchargeFees || [];
      // surcharge: true 补充报价 false 按单报价
      if (this.quoteDetail?.surcharge) {
        if (this.status === "2") {
          surchargeData = surchargeFees;
        }
        if ((["8"].includes(this.status) || (this.waybillQuoteBargain && this.surcharge)) && surchargeFees?.length > 0) {
          this.quoteDetail.surchargeFees.map((item) => {
            item.typeDisabled = true;
          });
        }

        let bargainLabel = this.waybillQuoteBargain && this.surcharge ? '议价' : null;
        let bargainLabelOption = {
          title: bargainLabel || STATUS_LABEL[this.status],
          typeName: bargainLabel || STATUS_LABEL[this.status],
          typeDisabled: true
        };
        // 补充报价-补充报价/被拒绝待审核、审核报价、审核报价-议价的状态，补充费用数据源
        if (
          (this.status === "1" && this.quoteDetail.status != 8)
          || (this.status === "11" && this.quoteDetail.status != 8)
          || (this.status === "11" && this.waybillQuoteBargain && this.surcharge && this.quoteDetail.status != 8)
        ) {
          surchargeData = surchargeFees?.length > 0
            ? [...this.quoteDetail.surchargeFees, { ...bargainLabelOption }]
            : [{ ...bargainLabelOption }];
          surchargeData =
            this.quoteDetail?.auditingFees && this.quoteDetail?.auditingFees?.length > 0
              ? [...surchargeData, ...this.quoteDetail.auditingFees]
              : surchargeData;
        }
        // 补充报价-议价待审核、补充报价-议价的状态，补充费用数据源
        if (
          (this.status === "1" && this.quoteDetail.status === 8) ||
          this.status === "8" || this.status === '18' ||
          (this.status === '8' && this.waybillQuoteBargain && this.surcharge) ||
          (this.status === "11" && this.quoteDetail.status === 8) ||
          (this.status === '11' && this.waybillQuoteBargain && this.surcharge && this.quoteDetail.status === 8)
        ) {
          surchargeData = surchargeFees?.length > 0
            ? [...this.quoteDetail.surchargeFees, { ...bargainLabelOption }]
            : [{ ...bargainLabelOption }];
          surchargeData =
            this.quoteDetail?.bargainFees && this.quoteDetail?.bargainFees?.length > 0
              ? [...surchargeData, ...this.quoteDetail.bargainFees]
              : surchargeData;
        }
        // 补充报价被拒绝的状态，补充费用数据源
        if (this.status === "3") {
          let list = [];
          if (surchargeFees?.length > 0) {
            list = surchargeFees.map((item) => {
              item.typeDisabled = true;
              return item;
            });
          }
          surchargeData =
            list.length > 0
              ? [...list, { ...bargainLabelOption }]
              : [{ ...bargainLabelOption }];
          surchargeData =
            this.quoteDetail?.rejectedFees && this.quoteDetail?.rejectedFees?.length > 0
              ? [...surchargeData, ...this.quoteDetail.rejectedFees]
              : surchargeData;
        }
        // 已关闭
        if (["32", "14"].includes(this.status)) {
          let list = [];
          if (surchargeFees?.length > 0) {
            list = surchargeFees.map((item) => {
              item.typeDisabled = true;
              return item;
            });
          }
          surchargeData =
            list.length > 0
              ? [...list, { ...bargainLabelOption }]
              : [{ ...bargainLabelOption }];
          surchargeData =
            this.quoteDetail?.closedFees && this.quoteDetail?.closedFees?.length > 0
              ? [...surchargeData, ...this.quoteDetail.closedFees]
              : surchargeData;
        }
      } else {
        surchargeData = surchargeFees.length ? surchargeFees : this.quoteDetail?.bargainFees;
      }
      //附加费用相加
      surchargeData && surchargeData.forEach((element) => {
        if (["2"].includes(this.status) && !element.add) element.typeDisabled = true;
        if (element.type) element.disabled = true;
        bargainTotal += Number(element.money) || 0;
      });
      // 总补充费用
      this.bargainTotal = bargainTotal;
      this.feeTypeArr = surchargeData && surchargeData.map((item) => {
        if (!item.typeDisabled) {
          return item.type;
        }
      });

      return surchargeData || [];
    },
    // 运单+补充费用的合计
    totalFee () {
      let num = returnThousandDigit(
        Number(this.quoteTotal) + Number(this.bargainTotal),
        2
      );
      return num || 0
    },
    //预付费用
    payList () {
      let payArr = []
      if (this.quotationId && this.quoteDetail) {
        payArr = [{
          arrivePayFee: this.quoteDetail?.arrivePayFee || 0, //货到付款
          collectionFee: this.quoteDetail?.collectionFee || 0, //代收货款
          prepayFee: this.quoteDetail?.prepayFee || 0 //预付款
        }];
      }
      // 议价-议价前费用显示
      if (this.status === '8' || this.waybillQuoteBargain) {
        payArr[0].arrivePayFeeBefore = this.quoteDetail?.arrivePayFeeBefore
        payArr[0].collectionFeeBefore = this.quoteDetail?.collectionFeeBefore
        payArr[0].prepayFeeBefore = this.quoteDetail?.prepayFeeBefore
      }
      return payArr || [];
    },
    // 合约匹配弹窗列
    matchColumn () {
      let column = [];
      if (this.wayBillColumn.length) {
        column = JSON.parse(JSON.stringify(this.wayBillColumn));
        column = column.splice(0, column.length - 1);
        column.push({
          name: "surchargeFee",
          label: "补充费用",
          type: 'text'
        }, {
          name: "totalFee",
          label: "总费用",
          type: 'total'
        })
      }
      return column;
    },
    matchSurchargeData () {
      // let asur = this.$refs.bargainRef?.tableData;
      // console.log("====<", asur, this.addCostList)
      // return asur;
      return this.quoteDetail?.surchargeFees || []
    },
    // true:发起方、false:审核方
    initiator () {
      return this.quoteDetail?.originator;
    },
    matchData () {
      if (this.matchId) {
        let data = JSON.parse(JSON.stringify(this.priceList));
        let surchargeFeeTotal = 0;
        this.matchSurchargeData.forEach((ele) => {
          surchargeFeeTotal += Number(ele.money) || 0;
        });
        data[0].surchargeFee = surchargeFeeTotal;
        data[0].totalFee = returnThousandDigit(data[0].quoteTotal + data[0].surchargeFee, 2);
        return data;
      }
      return [];
    },
  },
  created () {
    // 运单的报价状态
    if (this.$route.query?.status) {
      this.status = this.$route.query?.status.toString();
    }
    if (this.$route.query?.status === 0) {
      this.status = '0'
    }
    this.quotationId = Number(this.$route.query.quotationId) || null;
    this.getTransportDetail();
    this.trackInformation();
    if (this.quotationId) {
      this.getDetail();
    }
  },
  methods: {
    // 获取运单信息
    async getTransportDetail () {
      let { data } = await transport.getDetail(this.$route.query.waybillId);

      this.refresh = data?.waybillPrice?.refresh;
      data.waybillCache.calculateValue = data.waybillCache.calculateValue
        ? returnThousandDigit(data.waybillCache.calculateValue, 2)
        : 0;

      // 运单计费模式为重量 计费单位为吨
      if (
        data.transportRequirement?.chargeMode === 1 &&
        data.transportRequirement?.pricingUnit === 2
      ) {
        data.waybillCache.calculateWeight = volumeOrWeightConversion(
          0,
          data.waybillCache.calculateWeight
        );
      }
      // 运单计费模式为体积 计费单位为升
      if (
        data.transportRequirement?.chargeMode === 2 &&
        data.transportRequirement?.pricingUnit === 4
      ) {
        data.waybillCache.calculateVolume = volumeOrWeightConversion(
          1,
          data.waybillCache.calculateVolume
        );
      }
      // 运输模式为整车 车型为其他车型
      if (
        data.transportRequirement?.transportMode === 2 &&
        data.transportRequirement?.vehicleLength === 999
      ) {
        data.transportRequirement.vehicleLength = "其他";
      }
      if (data.attachments) {
        this.files = data.attachments.filter((x) => x.type === 2);
      }
      this.quoteData = {
        contractNo: data.contractNo,
        createAt: data.createAt,
        createName: data.createBy.name,
        customerName: data.customer.showCustomerName,
        carrierName: data?.carrier?.carrierName,
        driverName: data?.carrier?.driverName
      };
      this.carrierExtraType = data?.carrier?.carrierExtraType
      this.waybillDetails = data;
    },
    // 获取报价详情
    async getDetail () {
      let { data } = await quotation.getQuotation(this.quotationId);
      this.quoteDetail = data;
      this.minimumFee = data?.minimumFee || 0;
      this.matchId = data?.matchId;
      this.remarks = data?.remarks;
    },
    // 报价前置效验
    async validateQuotation ({ val, message, postData }) {
      let { data } = await quotation.validateQuote(this.$route.query.subjectId);
      // 校验是否已发送报价单
      if (!data.validate) {
        if (data.flag === 1) {
          this.$confirm("已向您发起了报价，是否去审核?", "提示", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            // this.routerLink("11", data.quotationId);
            this.status = '11';
            this.quotationId = data.quotationId;
          });
        } else if (data.flag === 2) {
          this.$confirm("报价单正在处理中，不能重复报价", "提示", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            this.handelClose()
          });
        }
      } else {
        this.confirmAction(val, message, postData);
      }
    },
    returnData (val) {
      this.priceList = [{ ...val }];
    },
    // 运单报价费用合计
    handleQuoteTotal (type, val) {
      this.quoteTotal = type === 1 ? val : this.quoteTotal;
      this.bargainTotal = type === 2 ? val : this.bargainTotal;
    },
    // 触发事件
    handleSubmit (val) {
      if (val === 40) {
        return this.confirmAction(val, "确认撤回报价单");
      }
      if (val === 30) {
        return this.confirmAction(val, "是否确认同意报价单");
      }
      if (val === 60) {
        this.visible = true;
        return
      }
      if (val === 70) {
        this.bargainSwitch = true;
        return
      }
      if (val === 110) {
        return this.$confirm("确认关闭报价单？", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.closeQuotation();
        });
      }
      let waybillCost = this.$refs.transportQuote.tableData[0];
      if (Object.keys(waybillCost).length === 0) {
        return this.$message.warning("请至少填写一项报价费用");
      }
      let payTypeData = this.$refs.payType.tableData;
      let num = 0;
      for (let key in payTypeData[0]) {
        if (['arrivePayFee', 'collectionFee', 'prepayFee'].includes(key)) {
          num += Number(payTypeData[0][key]);
        }
      }
      if (num > (Number(this.quoteTotal) + Number(this.bargainTotal))) {
        this.$confirm("预付款,货到付款,代收货款的总额大于总金额, 是否继续?", {
          title: "提示",
          type: "warning"
        })
          .then(() => {
            this.create(val);
          })
      } else {
        this.create(val);
      }
    },
    // 二次确认框
    confirmAction (val, message, postData) {
      this.$confirm(
        `${this.waybillQuoteBargain || this.bargainSwitch
          ? "当前状态为议价，确认是否发送议价"
          : `${message}？`
        }`,
        "提示",
        {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        // 按单报价-发送
        if (val === 10)
          this.save(postData, true);
        // 同意
        if (val === 30)
          this.requestFunction("agree", { quotationId: this.quotationId });
        // 撤回
        if (val === 40)
          this.requestFunction("recall", { quotationId: this.quotationId });
        // 议价 
        if (val === 50)
          this.requestFunction("bargain", { ...postData, method: this.surcharge ? 'SURCHARGE' : 'STANDARD' });
        // 补充报价-发送，补充报价：被拒绝-发送
        if ([90, 100].includes(val))
          this.save(postData, true, true);
      });
    },
    //创建报价单
    create (val) {
      // 补充费用
      let bargainFee = [];
      let bargainFlag = false; // 附加费金额是否为空
      if (!this.carrierExtraType || (this.carrierExtraType && (this.surcharge || this.quoteDetail.status === 2))) {
        this.$refs.bargainRef.tableData.forEach((item) => {
          console.log("===>num", item)
          if ((item.money != 0 && !item.money && !item.title) || item.money === "" || (item.money && Number.isNaN(Number(item.money)))) {
            bargainFlag = true;
          }
          let obj = {
            money: item.money,
            type: item.type,
            remarks: item.remarks
          };
          if (
            !((["2", "3", "0"].includes(this.status) || (this.waybillQuoteBargain && this.surcharge)) && item.typeDisabled) &&
            !item.title
          ) {
            bargainFee.push(obj);
          }
        });
      }
      if (bargainFlag) {
        return this.$message.warning("补充费用不能为空");
      }
      // 付款方式
      let payTypeData = this.$refs.payType.tableData;
      // 请求参数
      let postData = {
        surchargeFees: bargainFee, // 补充费用
        arrivePayFee: payTypeData[0].arrivePayFee || 0, //货到付款
        collectionFee: payTypeData[0].collectionFee || 0, //代收货款
        prepayFee: payTypeData[0].prepayFee || 0, //预付款
        remarks: this.remarks,
        subjectId: this.$route.query.subjectId,
        quotationId: this.quotationId
      };
      // 运单费用
      let transportCost = this.$refs.transportQuote.tableData[0];
      for (let key in transportCost) {
        if (["less", "full"].includes(key)) {
          postData.transportFee = transportCost[key] || 0;
        } else {
          postData[`${key}Fee`] = transportCost[key] || 0;
        }
        if (key === "onLoad") postData.loadFee = transportCost[key] || 0;
        if (key === "offLoad") postData.unloadFee = transportCost[key] || 0;
      }
      // 保存
      if (val === 20) {
        this.save(postData, false);
      }
      //发送
      if ([10, 90].includes(val)) {
        if (val === 90 &&
          postData.surchargeFees.length < 1 &&
          postData.arrivePayFee === Number(this.quoteDetail.arrivePayFee) &&
          postData.collectionFee === Number(this.quoteDetail.collectionFee) &&
          postData.prepayFee === Number(this.quoteDetail.prepayFee)) {
          return this.$message.warning("您还未输入报价信息，请检查输入的值");
        }
        this.validateQuotation({ val, message: "确认发送", postData });
      }
      if ([50, 100].includes(val)) {
        this.confirmAction(val, "确认发送", postData);
      }
    },
    //保存
    async save (postData, flag, isAddSurcharge) {
      this.loading = true;
      let response;
      // isAddSurcharge true：补充报价 false：按单报价
      if (isAddSurcharge) {
        response = await quotation.addSurcharge({
          quotationId: this.quotationId,
          ...postData,
          submit: flag
        })
          .catch(err => {
            this.loading = false
          });
      } else {
        response = this.quotationId
          ? await quotation.updateQuotation(this.quotationId, postData).catch(err => { this.loading = false })
          : await quotation.createQuotation(postData).catch(err => { this.loading = false });
      }
      let { code, data } = response;
      // flag true：发送 false：保存
      if (code === 0 && flag && !isAddSurcharge) {
        // 调用保存接口后，根据返回的quotationId调用发送接口
        this.requestFunction("sendQuotation", {
          quotationId: data.quotationId
        });
      } else {
        this.loading = false;
        this.handelClose();
      }
    },
    // 调用请求 requestType: ['sendQuotation': 发送, 'recall': 撤回, 'agree': 同意, 'bargain': 议价]
    async requestFunction (requestType, postData) {
      this.loading = true;
      let { code, message } = await quotation[requestType](postData)
        .catch(err => {
          this.loading = false;
        });
      this.$message[code === 0 ? "success" : "error"](message);
      this.loading = false;
      if (requestType === 'bargain' && this.bargainSwitch) {
        this.$router.back();
      } else {
        this.handelClose();
      }
    },
    // 关闭报价单
    async closeQuotation () {
      let { code } = await quotation.discard({ quotationId: this.quotationId, surcharge: this.quoteDetail?.hasSurcharge });
      if (code === 0) {
        this.handelClose();
      }
    },
    // 跟踪信息
    async trackInformation () {
      if (this.quotationId) {
        let { code, data } = await track.information(this.quotationId, 'quotation');
        if (code === 0 && data.length) {
          data.map(item => {
            if (item.message.indexOf('，') != -1 && item.message.lastIndexOf('】')) {
              item.timestamp = item.message.slice(0, item.message.indexOf('，'))
              item.date = item.message.slice(item.message.indexOf('，') + 1, item.message.lastIndexOf('】') + 1)
              item.content = item.message.includes('】') ? item.message.slice(item.message.lastIndexOf('】') + 1) : item.message.slice(item.message.indexOf('，') + 1)
            }
          })
          this.track = data
          this.isTrack = true
        }
      }
    },
    // 返回
    handelClose () {
      if (this.bargainSwitch) {
        this.bargainSwitch = false;
      } else {
        if (this.closeLabel === "返回") {
          this.$router.back();
        } else {
          window.close();
        }
      }
    }
  }
};
